package org.asiainfo.file.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.asiainfo.file.config.properties.FtpProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ftp配置类
 *
 * @author dotor-ww
 */
@Configuration
@EnableConfigurationProperties(FtpProperties.class)
@ConditionalOnProperty(value = "ftp.enabled", havingValue = "true")
@Slf4j
public class FtpConfig {

    /**
     * 创建FTPClient bean
     *
     * @param ftpProperties 配置
     * @return ftpClient
     */
    @Bean
    public FTPClient ftpClient(FtpProperties ftpProperties) {
        // 创建FTPClient对象（对于连接ftp服务器，以及上传和上传都必须要用到一个对象）
        FTPClient ftpClient = new FTPClient();
        // 设置连接超时时间
        ftpClient.setConnectTimeout(ftpProperties.getConnectTimeout());
        // 设置ftp字符集
        ftpClient.setControlEncoding("utf-8");
        // 设置被动模式，文件传输端口设置,否则文件上传不成功，也不报错
        ftpClient.enterLocalPassiveMode();
        try {
            // 连接ftp(当前项目所部署的服务器和ftp服务器之间可以相互通讯，表示连接成功)
            ftpClient.connect(ftpProperties.getHost());
            // 输入账号和密码进行登录
            ftpClient.login(ftpProperties.getUsername(), ftpProperties.getPassword());
            // 接受状态码(如果成功，返回230，如果失败返回503)
            int replyCode = ftpClient.getReplyCode();
            // 根据状态码检测ftp的连接，调用isPositiveCompletion(reply)-->如果连接成功返回true，否则返回false
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.error("创建ftpClient失败，连接 {} ftp失败", ftpProperties.getHost());
                // 连接失败，断开连接
                ftpClient.disconnect();
                return null;
            }
        } catch (Exception e) {
            log.error("ftpClient连接失败: {}", e.getMessage());
            return null;
        }
        return ftpClient;
    }
}
